import React, { useState, useEffect, useRef } from 'react';
import { Dimensions, FlatList, StyleSheet, TouchableOpacity, Text, Button, View, Image, ImageBackground, ScrollView, TextInput } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { AntDesign } from '@expo/vector-icons';
import moment from 'moment';
import axios from '../../api/axios';
import { useAuth, baseURL } from '../../context/AuthProvider'

const Btn = ({ children, style, color, ...rest }) => {
    return (
        <TouchableOpacity {...rest} style={
            {
                justifyContent: 'center',
                alignItems: 'center',
                ...style
            }
        }>
            <Text style={{ color: color ? color : '#fff' }}>{children}</Text>
        </TouchableOpacity>
    )
}
const { width, height } = Dimensions.get('window');

const NewsComment = ({ navigation, route }) => {
    const { user } = useAuth();
    const [news, setNews] = useState([]);
    const [comment, setComment] = useState([]);
    const [content, setContent] = useState('');
    const [father, setFather] = useState('');
    const newsid = route.params.newsid;
    const input1 = useRef(null);
    const addChildComment = (id) => {
        setFather(id);
        input1.current.focus();
    }
    const addComment = () => {
        if (father) {
            axios.post('/newscomment/comment', {
                userid: user.userid,
                content: content,
                addtime: new Date().getTime(),
                newsid: newsid,
                parentid: father,
            }).then(res => {
                console.log(res);
                setFather('');
                setContent('');
                axios.post('/news/comment', {
                    newsid: newsid
                }).then(res => {
                    console.log(1111);
                    console.log(res.data.parent_comment_id);
                    if (res.code == 200) {
                        setComment(res.data);
                    }
                })
            })
        }
        else {
            axios.post('/newscomment/comment', {
                userid: user.userid,
                content: content,
                addtime: new Date().getTime(),
                newsid: newsid,
            }).then(res => {
                console.log(res);
                setContent('');
                axios.post('/news/comment', {
                    newsid: newsid
                }).then(res => {
                    console.log(1111);
                    console.log(res.data.parent_comment_id);
                    if (res.code == 200) {
                        setComment(res.data);
                    }
                })
            })
        }
    }
    useEffect(() => {
        AsyncStorage.getItem('commentNews').then(
            data => {
                if (data) {
                    setNews(JSON.parse(data))
                }
            }
        )
        // 动态内容获取
        axios.post('/news/single', {
            newsid: newsid
        }).then(res => {
            if (res.code == 200) {
                // console.log(123);
                AsyncStorage.setItem('commentNews', JSON.stringify(res.data))
                setNews(res.data)
                // console.log(res.data);
            }
            // console.log(res);
        }).catch(e => {
            console.log('出错了', e);
        });
        // 动态评论获取
        axios.post('/news/comment', {
            newsid: newsid
        }).then(res => {
            console.log(1111);
            console.log(res.data.parent_comment_id);
            if (res.code == 200) {
                setComment(res.data);
            }
        })
    }, [])
    const deleteComment = (id) => {
        axios.post('/newscomment/delete', {
            newscom_id: id,
        }).then(res => {
            console.log(res);
            if (res.code == 200) {
                axios.post('/news/comment', {
                    newsid: newsid
                }).then(res => {
                    if (res.code == 200) {
                        setComment(res.data);
                    }
                })
            }
        })
    }
    return (
        <View style={{ justifyContent: 'space-between', width: '100%', height: height - 103 }}>
            <ScrollView style={{ width: '100%', height: '100%', }}>
                <View style={{ minHeight: height * 0.6 }}>
                    <View>
                        {news && news.map((item) => {
                            return <View
                                key={item.newsid}
                                style={{
                                    minHeight: 150,
                                    backgroundColor: '#FFFFFF',
                                }}>
                                <View style={{
                                    width: width, height: 65,
                                    flexDirection: 'row',
                                    paddingLeft: 15,
                                    backgroundColor: 'rgba(203,242,203,0.5)',
                                    alignItems: 'center',
                                    justifyContent: 'space-between'
                                }}>
                                    <View style={{ alignItems: 'center', flexDirection: 'row', }}>
                                        {item.avatar ?
                                            <Image style={{ width: 56, height: 56, borderRadius: 30 }} source={{ uri: baseURL + item.avatar }} />
                                            :
                                            <Image style={{ width: 55, height: 55, borderRadius: 30 }} source={require('../../../images/mine/1.jpg')} />
                                        }
                                        <View style={{ paddingLeft: 10 }}>
                                            <Text style={{ fontSize: 15.5 }}>{item.nickname}</Text>
                                            <Text style={{ fontSize: 13, color: '#bbb' }}>{moment(item.addtime).format("YYYY-MM-DD HH:mm")}</Text>
                                        </View>
                                    </View>
                                </View>
                                <View style={{ alignItems: 'center' }}>
                                    <View style={{ width: width * 0.8, marginTop: 15, }}>
                                        <Text>{item.newstext}</Text>
                                        {
                                            item.newsimg ?
                                                <View style={item.newsimg ? { flexDirection: 'row', marginTop: 10, } : { display: 'none' }}>
                                                    {
                                                        item.newsimg.map((item1) => {
                                                            return <Image key={item1.newsimgid} style={{ width: 110, height: 110, marginRight: 10 }} source={{ uri: baseURL + item1.newsimgs }} />
                                                        })
                                                    }
                                                </View>
                                                : <></>
                                        }
                                        <View style={{
                                            marginTop: 5, marginBottom: 5,
                                            backgroundColor: 'rgba(203,242,203,0.8)',
                                            height: 25, width: 55,
                                            justifyContent: 'center',
                                            alignItems: 'center',
                                            borderRadius: 13
                                        }}>
                                            <Text style={{ color: '#2A5F6b' }}>#{item.cropname}</Text>
                                        </View>
                                    </View>
                                </View>
                            </View>
                        })}
                    </View>
                    <View>
                        <View style={{
                            width: width,
                            height: 33,
                            justifyContent: 'center',
                        }}>
                            <Text style={{
                                lineHeight: 30, height: 30, fontSize: 18,
                                fontWeight: 'bold', color: '#2A5F6b', borderLeftWidth: 3,
                                borderLeftColor: '#42C05C', paddingLeft: 10,
                                marginLeft: 7
                            }}>评论</Text>
                        </View>
                        {comment.length == 0 ?
                            <View style={{
                                alignItems: 'center',
                                height: height * 0.1,
                                justifyContent: 'center',
                            }}>
                                <Text style={{
                                    fontSize: 18,
                                    color: '#2A5F6b'
                                }}>
                                    暂无评论
                            </Text>
                            </View>
                            : <></>}
                        {
                            comment && comment.map((item) => {
                                return <View
                                    key={item.newscom_id}
                                    style={!item.parent_comment_id ? {
                                        backgroundColor: '#FFFFFF',
                                    } : { display: 'none' }}>
                                    <View style={{
                                        width: width, height: 55,
                                        flexDirection: 'row',
                                        paddingLeft: 15,
                                        // backgroundColor: 'rgba(203,242,203,0.5)',
                                        alignItems: 'center',
                                        justifyContent: 'space-between'
                                    }}>
                                        <View style={{ alignItems: 'center', flexDirection: 'row' }}>
                                            {item.avatar ?
                                                <Image style={{ width: 45, height: 45, borderRadius: 22 }} source={{ uri: baseURL + item.avatar }} />
                                                :
                                                <Image style={{ width: 45, height: 45, borderRadius: 22 }} source={require('../../../images/mine/1.jpg')} />
                                            }
                                            <View style={{ paddingLeft: 10 }}>
                                                <Text style={{ fontSize: 15.5 }}>{item.nickname}</Text>
                                                <Text style={{ fontSize: 13, color: '#bbb' }}>{moment(item.create_time).format("YYYY-MM-DD HH:mm")}</Text>
                                            </View>
                                        </View>
                                        <View style={{ marginRight: width * 0.04 }}>
                                            <MaterialCommunityIcons name="comment-processing-outline" size={29} color="black" onPress={() => addChildComment(item.newscom_id)} />
                                        </View>
                                    </View>
                                    <View style={{ width: width, minHeight: 30, justifyContent: 'space-between', marginBottom: 5, flexDirection: 'row' }}>
                                        <Text style={{ marginLeft: '4.5%', lineHeight: 25 }}>{item.content}</Text>
                                        <MaterialCommunityIcons name="delete-empty-outline" size={25} color="rgb(203,242,183)"
                                            style={item.userid == user.userid ? { marginRight: '4.5%' } : { display: 'none' }}
                                            onPress={() => { deleteComment(item.newscom_id) }}
                                        />
                                    </View>
                                    <View style={{ alignItems: 'center', paddingBottom: 5 }}>
                                        {
                                            comment.map((item1, index) => {
                                                if (item1.parent_comment_id == item.newscom_id) {
                                                    return (
                                                        <View
                                                            key={index}
                                                            style={{
                                                                flexDirection: 'row', width: width * 0.88,
                                                                backgroundColor: 'rgba(203,242,203,0.22)',
                                                                padding: 3,
                                                                paddingLeft: 8, justifyContent: 'space-between'
                                                            }}>
                                                            <View style={{ flexDirection: 'row' }}>
                                                                <Text style={{ lineHeight: 25, color: '#2A5F6b' }}>{item1.nickname}: </Text>
                                                                <Text style={{ lineHeight: 25, }}> {item1.content}</Text>
                                                            </View>
                                                            <MaterialCommunityIcons name="delete-empty-outline" size={23} color="#2A5F6b"
                                                                style={item1.userid == user.userid ? { marginRight: '3%' } : { display: 'none' }}
                                                                onPress={() => { deleteComment(item1.newscom_id) }} />
                                                        </View>)
                                                }
                                            })
                                        }
                                    </View>
                                </View>
                            })
                        }
                    </View>
                </View>

            </ScrollView>

            <View style={styles.inputBox}>
                <TextInput
                    ref={input1}
                    autoFocus={false}
                    style={styles.input}
                    // multiline={true}
                    placeholder="输入你想评论的内容"
                    value={content}
                    onChangeText={text => setContent(text)}
                    // editable={false}
                />
                <Btn style={styles.uploadBtn}
                    color={'#fff'}
                    onPress={addComment}
                >
                    <Text style={{ fontSize: 16 }}>发布</Text>
                </Btn>
            </View>

        </View>
    )
}
const styles = StyleSheet.create({
    input: {
        width: '80%',
        minHeight: 45,
        // maxHeight: 200,
        color: '#2A5F69',
        paddingLeft: 15,
        // marginTop: 4,
        fontSize: 18,
    },
    inputBox: {
        width: '100%',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        backgroundColor: '#FFF',
        minHeight: height * 0.06,
        position: 'absolute',
        marginTop: height - 103,
        borderTopWidth: 1,
        borderTopColor: 'rgb(203,242,203)'
    },
    uploadBtn:{
        width: width * 0.13,
        height: 35,
        backgroundColor: '#42C05C',
        borderRadius: 10,
        marginRight: 15
    },
})

export default NewsComment
